import React, { useEffect, useState } from "react";
import RNMMKV from "../../Native/Module/RNMMKV.ts";

import {
  Button, StyleSheet,
  Text,
  TextInput,
  ToastAndroid,
  View
} from "react-native";
import { NavigationProp, useNavigation } from "@react-navigation/native";
import Main from "../Main";

type Account = {
  phone?: string;
  password?: string;
};


const styles = StyleSheet.create({
  inputStyle: {
    height: 40,
    margin: 16,
    borderColor: "gray",
    borderWidth: 1,
    fontSize: 15
  },
  buttonStyle: {
    marginHorizontal: 32,
    marginTop: 16
  }
});

type Props = {
  navigation: NavigationProp<ReactNavigation.RootParamList>
}

const Login = (props: Props) => {
  // const [account, setAccount] = useState<Account>({});

  const [phoneBorderColor, setPhoneBorderColor] = useState("gray");
  const [passwordBorderColor, setPasswordBorderColor] = useState("gray");

  const account: Account = {};

  function checkPhone(phone: string | undefined) {
    if (!phone) {
      ToastAndroid.show("请输入手机号码", ToastAndroid.SHORT);
      setPhoneBorderColor("red");
      return false;
    }
    if (phone.length != 11) {
      ToastAndroid.show("手机号格式不正确", ToastAndroid.SHORT);
      setPhoneBorderColor("yellow");
      return false;
    }
    setPhoneBorderColor("gray");
    return true;
  }

  function passwordVerify(password: string) {
    return password.length > 0 && password.length >= 6;
  }

  function checkPassword(password: string | undefined) {
    if (!password) {
      ToastAndroid.show("请输入密码", ToastAndroid.SHORT);
      setPasswordBorderColor("red");
      return false;
    }
    if (!passwordVerify(password)) {
      ToastAndroid.show("密码格式不正确", ToastAndroid.SHORT);
      setPasswordBorderColor("yellow");
      return false;
    }
    setPasswordBorderColor("gray");
    return true;
  }

  function handleLogin() {
    console.log(`phone=${account.phone}`);
    console.log(`password=${account.password}`);
    const phoneResult = checkPhone(account.phone);
    if (!phoneResult) return;
    const passwordResult = checkPassword(account.password);
    if (!passwordResult) return;
    RNMMKV.saveBoolean("is_login", true);
    RNMMKV.saveString("phone", account.phone);
    props.navigation.navigate(Main);
  }

  useEffect(() => {
    console.log("view layout change");
  });

  return <View>
    <TextInput
      style={{ ...styles.inputStyle, borderColor: phoneBorderColor }}
      keyboardType={"numeric"}
      placeholder="请输入手机号"
      onChangeText={text =>
        account.phone = text
      }
    />
    <TextInput
      style={{ ...styles.inputStyle, borderColor: passwordBorderColor }}
      placeholder="请输入密码"
      textContentType="newPassword"
      keyboardType="visible-password"
      onChangeText={text =>
        account.password = text
      }
    />
    <View style={styles.buttonStyle}>
      <Button
        title="登录"
        onPress={handleLogin} />
    </View>
  </View>;
};

export default Login;
